昨天註冊好了ThingSpeak,那今天就使用Python將DHT11資料傳送上去吧!
sudo pip3 install paho-mqtt(Python3)
sudo pip install paho-mqtt(Python)
請選擇安裝
import RPi.GPIO as GPIO
import dht11
from time import sleep
import paho.mqtt.publish as publish
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
dht = dht11.DHT11(pin = 4)
mqttHost = "mqtt.thingspeak.com"
channelID = "870677"
apiKey = "JAZ0DXU6TLNH5SI9"
tTransport = "websockets"
tPort = 80
tTLS = None
topic = "channels/" + channelID + "/publish/" + apiKey
def getSensorData():
r = dht.read()
if r.is_valid():
return(str(r.temperature), str(r.humidity))
else:
return(str(-1), str(-1))
while True:
try:
T, RH = getSensorData()
print(T, RH)
if T != '-1' and RH != '-1':
tPayload = "field1=" + T + "&field2=" + RH
publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)
sleep(15)
else:
sleep(1)
except:
print('Error...')
break
3.開啟瀏覽器輸入ThingSpeak
終於大功告成了這是第一次自己完成30天,好不容易今後我也會繼續研究樹莓派!加油囉!
恭喜大大~以後我玩樹梅派的時候來拜讀一下大大的文章!!
Raspberry Pi我還覺得不夠所以打算繼續深入下去,你的JavaScript控制Arduino也不錯阿!
謝謝大大~一起玩下去~XD